package com.cyh.job.service.impl;

import com.cyh.job.dao.JobDao;
import com.cyh.job.entity.QuartzEntity;
import com.cyh.job.entity.ReturnPage;
import com.cyh.job.service.JobService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cyh
 * @since 2018-08-07
 */
@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobDao jobDao;

    private static final Logger logger = LoggerFactory.getLogger(JobServiceImpl.class);

    @Override
    public ReturnPage<QuartzEntity> findJobList(QuartzEntity quartzEntity) {
        Integer total = jobDao.getTotal(quartzEntity);
        if (total != null){
            List<QuartzEntity> jobList = jobDao.findJobList(quartzEntity);
            return ReturnPage.create(total, jobList);
        }
        return  ReturnPage.empty();
    }

    @Override
    public Integer getJobCount() {
        return null;
    }

    @Override
    public void saveOrUpdateJob(QuartzEntity quartzEntity, boolean isAdd) throws Exception {
        //如果是修改一个job, 删除原有的job， 继续插入
        if (!isAdd){
            delete(quartzEntity);
        }
        Class cls = Class.forName(quartzEntity.getJobClassName());
        //设置job详情
        JobDetail detail = JobBuilder.newJob(cls).withIdentity(quartzEntity.getJobName(), quartzEntity.getJobGroup())
                .withDescription(quartzEntity.getDescription()).build();
        //设置触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzEntity.getCronExpression());
        Trigger trigger = TriggerBuilder.newTrigger().
                withIdentity(quartzEntity.getJobName(), quartzEntity.getJobGroup())
                .startNow().withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(detail, trigger);
    }

    @Override
    public void delete(QuartzEntity quartzEntity) {
        try {
            TriggerKey tkey = new TriggerKey(quartzEntity.getTriggerName(), quartzEntity.getTriggerGroup());
            scheduler.pauseTrigger(tkey);
            scheduler.unscheduleJob(tkey);
            scheduler.deleteJob(JobKey.jobKey(quartzEntity.getJobName(), quartzEntity.getJobGroup()));
            logger.info("----------------------------删除掉了job"+quartzEntity.getJobName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
